package com.yueya.common.action;

import java.util.HashMap;
import java.util.Map;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.JsonKit;
import com.yueya.basic.token.model.Token;
import com.yueya.common.constant.BaseConstant;
import com.yueya.common.constant.CodeConst;

/**
 * API拦截器
 */
public class ApiInterceptor implements Interceptor {

	public void intercept(Invocation inv) {
		Map<String, Object> map = new HashMap<String, Object>();
		Controller c = inv.getController();
		
		// 从请求头获取token
		String token = c.getRequest().getHeader(BaseConstant.TOKEN_KEY);
		System.out.println("token:" + token);
		// 校验token是否存在，是否有效
		if (token == null || "".equals(token)) {
			map.put("code", CodeConst.TOKEN_DISAPPEAR);
			map.put("msg", "缺少token");
			c.renderJson(JsonKit.toJson(map));
		} else {
			if(!Token.dao.checkToken(token)) {
				map.put("code", CodeConst.TOKEN_CHECKFAIL);
				map.put("msg", "token校验失败!");
				c.renderJson(JsonKit.toJson(map));
			}else {
				inv.invoke();
			}
		}

	}
 
}
